#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include "Log.hpp"
#include "Thread.hpp"
#include "Cond.hpp"
#include "Mutex.hpp"

namespace PoolModel
{
    using namespace ThreadModel;
    using namespace LogModel;
    using namespace CondModel;
    using namespace MutexModel;

    static const int gnum = 5;
    template <class T>
    class ThreadPool
    {
    private:
        void WakeUpAllThread(){
            Guard lockguard(&mutex);
            if(_sleepnum) _cond.Broadcast();
            Log(LogLevel::DEBUG)<<"唤醒所有线程";
        }

        void WakeUpOne(){
            _cond.Singal();
            Log(LogLevel::DEBUG)<<"唤醒一个线程";
        }
        ThreadPool(int num = gnum)
            : _pthread_num(gnum), _sleepnum(0), _isrunning(false)
        {
            for (int i = 0; i < num; i++)
            {
                _threads.emplace_back([this]()
                                      { HandlerTask(); });
            }
        }

        void Start()
        {
            if (_isrunning)
                return;
            _isrunning = true;
            for (auto &thread : _threads)
            {
                thread.Start();
                LOG(LogLevel::INFO) << "start new thread success: " << thread.Name();
            }
        }
        ThreadPool(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool &a) = delete;

    public:
        static ThreadPool<T> *GetInstance()
        {
            if (inc == nullptr)
            {
                Guard lockguard(_mutex);
                Log(LogLevel::DEBUG) << "获取单例...";
                if (inc == nullptr)
                {
                    Log(LogLevel::DEBUG) << "首次使用单例, 创建之....";
                    inc = new ThreadPool<T>();
                    inc->Start();
                }
            }
            return inc;
        }
        void stop(){
            if(!_isrunning) return;
            _isrunning = false;
            WakeUpAllThread();
        }
        void join(){
            for(auto thread:_threads){
                thread.Join();
            }
        }

        void HandlerTask(){
            char name[128];
            pthread_getname_np(pthread_self(),name,sizeof(name));
            while(true){
                T t;
                Guard lockguard(_lock);
                while(_taskq.empty()&&_isrunning){
                    _sleepnum++;
                    _cond.Wait(_lock);
                    _sleepnum--;
                }
                if(!_isrunning&&_taskq.empty()){
                    Log(LogLevel::INFO)<<name<<"线程池退出并且任务为空";
                    break;
                }
                t = _taskq.front();
                _taskq.pop();
            }
            t();
        }

        bool Equeque(cons T& in){
            if(_isrunning){
                Guard lockguard(_lock);
                _taskq.push(in);
                if(_sleepnum>0) WakeUpOne();
                return true;
            }
            return false;
        }
        ~Thread(){}
    private:
        // 线程，任务，互斥量，条件变量，任务，
        std::vector<Thread> _threads;
        Mutex _lock;
        Cond _cond;
        int _pthread_num;
        std::queue<T> _taskq;

        bool _isrunning;
        int _sleepnum;

        static ThreadPool<T> *inc;
        static Mutex _mutex;
    };
    template<typename T>
    ThreadPool<T> *ThreadPool<T>::inc = nullptr;
    template<typename T>//因为模板类的静态成员不能在类内直接初始化，必须在类外显式声明，声明在类内，定义在类外
    Mutex ThreadPool<T>::_mutex;
}